package com.example.znyt.manage.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.example.znyt.config.CosClientConfig;
import com.example.znyt.exception.BussinessException;
import com.example.znyt.exception.ErrorCode;
import com.example.znyt.manage.CosManager;
import com.example.znyt.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description TODO
 * @Date 2025/6/20 19:43
 * @Created by 12336
 */

@Slf4j
public abstract class PictureUploadTemplate {
    @Resource
    private CosManager cosManager;
    @Resource
    private CosClientConfig cosClientConfig;

    public final UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        //1.校验图片
        validPicture(inputSource);
        //2.图片上传地址
        String uuid = RandomUtil.randomString(16);
        //2.获取原始文件名
        String originFilename = getOriginFilename(inputSource);
        //3.拼接文件名(格式： 2023/06/17/uuid.jpg)
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, (FileUtil.getSuffix(originFilename)=="")?"png":FileUtil.getSuffix(originFilename));
        //4.拼接最终的上传路径(上传前缀/新文件名)
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);


        File file = null;
        try {
            //创建临时文件
            file = File.createTempFile(uploadPath, null);
            //处理文件来源
            processFile(inputSource, file);
            //上传图片
            PutObjectResult putObjectResult = cosManager.putObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> objectList = processResults.getObjectList();
            if(CollUtil.isNotEmpty(objectList)){
                CIObject compressedCiObject = objectList.get(0);
                CIObject thumbnailCiObject = compressedCiObject;
                if(objectList.size() > 1){
                    thumbnailCiObject = objectList.get(1);
                }
                //封装压缩后的返回结果
                return buildResult(originFilename, compressedCiObject, thumbnailCiObject);
            }
            //封装返回结果
            return buildResult(originFilename, file, uploadPath, imageInfo);
        } catch (Exception e) {
            log.error("图片上传到对象存储失败", e);
            throw new BussinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            deleteTempFile(file);
        }
    }


    /**
     *
     * @param inputSource
     * @return
     */
    protected abstract String getOriginFilename (Object inputSource);

    /**
     * 校验输入源
     * @param inputSource
     */
    protected abstract void validPicture (Object inputSource);

    /**
     * 处理输入源并生成本地临时文件
     * @param inputSource
     * @param file
     */
    protected abstract void processFile (Object inputSource, File file) throws Exception;

    /**
     * 删除临时文件
     * @param file
     */
    protected  void deleteTempFile(File file){
        if(file == null){
            return;
        }
        boolean deleteResult = file.delete();
        if(!deleteResult){
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    };

    /**
     * 封装返回结果
     * @param originFilename
     * @param file
     * @param uploadPath
     * @param imageInfo
     * @return
     */
    private UploadPictureResult buildResult(String originFilename, File file, String uploadPath, ImageInfo imageInfo) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = imageInfo.getWidth();
        int picHeight = imageInfo.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
        return uploadPictureResult;

    }

    /**
     * 新的封装返回结果方法
     * @param originFilename
     * @param compressedCiObject
     * @return
     */
//    private UploadPictureResult buildResult(String originFilename, CIObject compressedCiObject) {
//        UploadPictureResult uploadPictureResult = new UploadPictureResult();
//        int picWidth = compressedCiObject.getWidth();
//        int picHeight = compressedCiObject.getHeight();
//        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
//        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
//        uploadPictureResult.setPicWidth(picWidth);
//        uploadPictureResult.setPicHeight(picHeight);
//        uploadPictureResult.setPicScale(picScale);
//        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
//        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
//        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
//        return uploadPictureResult;
//    }

    private UploadPictureResult buildResult(String originFilename, CIObject compressedCiObject, CIObject thumbnailCiObject) {
        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        int picWidth = compressedCiObject.getWidth();
        int picHeight = compressedCiObject.getHeight();
        double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
        uploadPictureResult.setPicName(FileUtil.mainName(originFilename));
        uploadPictureResult.setPicWidth(picWidth);
        uploadPictureResult.setPicHeight(picHeight);
        uploadPictureResult.setPicScale(picScale);
        uploadPictureResult.setPicFormat(compressedCiObject.getFormat());
        uploadPictureResult.setPicSize(compressedCiObject.getSize().longValue());
        uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + compressedCiObject.getKey());
        uploadPictureResult.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
        return uploadPictureResult;
    }



}


